﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using uTorrentNetClient.ModelDesign.Contracts;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Composite.Regions;
using uTorrentNetClient.ModelDesign.Helper;
using Microsoft.Practices.Composite.Presentation.Commands;

namespace uTorrentNetClient.ModelDesign.Settings.Controller
{
    public class SettingsController : ISettingsController
    {
        private const string DIALOG = "Dialog";

        private IRegionManager _regionManager;
        private IUnityContainer _container;

        public DelegateCommand<SettingsCommandHelper> ShowSettingsCommand { get; private set; }

        public DelegateCommand<object> CloseSettingsCommand { get; private set; }

        public SettingsController(IRegionManager regionManager, IUnityContainer container)
        {
            _regionManager = regionManager;
            _container = container;

            ShowSettingsCommand = new DelegateCommand<SettingsCommandHelper>(b => showSettings(b));
            CloseSettingsCommand = new DelegateCommand<object>(closeSettings);
        }

        private void showSettings(SettingsCommandHelper o)
        {
            var region = _regionManager.Regions["Dialog"];
            var dialog = region.GetView(DIALOG);
            
            if (dialog == null)
            {
                var model = _container.Resolve<ISettingsModel>();
                model.AppSettings = o.AppSetting;
                model.WebClient = o.WebClient;
                model.SetGroups();
                _regionManager.Regions["Dialog"].Add(model.View, DIALOG);
            }
        }

        private void closeSettings(object o)
        {
            var region = _regionManager.Regions["Dialog"];
            var dialog = region.GetView(DIALOG);

            if (dialog != null)
            {
                region.Remove(dialog);
            }
        }
    }
}
